package user

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/micro/go-micro/v2/client/grpc"
	admin_user "goods_user_srv/proto/admin_user"
	"goods_web/utils"
	"net/http"
)

// 管理员登陆
func AdminLogin(c *gin.Context) {
	// 接收参数
	username := c.PostForm("username")
	password := c.PostForm("password")

	// fmt.Println(username, password)

	// 校验参数
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg": "参数不全",
		})
	}else {
		// 调用用户服务
		client := grpc.NewClient()
		adminUserService := admin_user.NewAdminUserService("go.micro.service.goods_user_srv", client)
		response, _ := adminUserService.AdminUserLogin(context.Background(), &admin_user.AdminUserRequest{
			Username: username,
			Password: password,
		})
		// fmt.Println(response)
		// 生成token
		token, e := utils.GenToken(response.UserName, utils.AdminUserTokenExpireDuration, utils.AdminUserSecretKey)
		fmt.Println(token)
		if e != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": response.Code,
				"msg": response.Msg,
			})

		}else {
			// fmt.Println(response.Code, response.Msg, response.UserName)
			c.JSON(http.StatusOK, gin.H{
				"code": response.Code,
				"msg": response.Msg,
				"user_name": response.UserName,
				"admin_token": token,
			})
		}


	}
}


// 用户列表
func AdminUserList(c *gin.Context) {
	// 接收参数
	currentPage := c.DefaultQuery("currentPage", "1")
	pageSize := c.DefaultQuery("pageSize", "5")

	// fmt.Println(currentPage, pageSize)

	// 调用服务
	client := grpc.NewClient()

	service := admin_user.NewAdminUserService("go.micro.service.goods_user_srv", client)
	response, e := service.FrontUserList(context.Background(), &admin_user.FrontUsersRequest{
		CurrentPage: utils.StrToInt32(currentPage),
		PageSize: utils.StrToInt32(pageSize),
	})
	if e != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": response.Code,
			"msg": response.Msg,
		})

	}else {
		// fmt.Println(response.FrontUser)
		c.JSON(http.StatusOK, gin.H{
			"code": response.Code,
			"front_users": response.FrontUser,
			"msg": response.Msg,
			"current_page": response.CurrentPage,
			"page_size": response.PageSize,
			"total": response.TotalPage,
		})
	}

	// 构造假数据
	//userList := []map[string]interface{}{
	//	{
	//		"email": "123@qq.com",
	//		"desc": "nihao",
	//		"status": 1,
	//		"create_time": "2021-4-2",
	//	},
	//	{
	//		"email": "123@qq.com",
	//		"desc": "nihao",
	//		"status": 1,
	//		"create_time": "2021-4-2",
	//	},
	//}
}